<script setup lang="ts">
import { formatDateTime } from "@/common/utils/datetime.ts"
import { createOrUpdateActivityDataApi, getActivityDetailApi } from "@@/apis/activity"
import { getToken } from "@@/utils/cache/cookies"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"
import { onBeforeUnmount, onMounted, ref, shallowRef } from "vue"
import SingleImageUpload from "./components/SingleImageUpload.vue"
import "@wangeditor/editor/dist/css/style.css"

defineOptions({
  name: "Editor"
})

const route = useRoute()
const router = useRouter()

const formInlineRef = ref<FormInstance | null>(null)
const formInline = reactive({
  title: "",
  content: "",
  font_color: "",
  image: ""
})

const formInlineRules = {
  title: [
    { required: true, message: "请输入活动标题", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }
  ],
  content: [
    { required: true, message: "请输入活动内容", trigger: "blur" }
  ],
  image: [
    { required: true, message: "请上传活动图片", trigger: "blur" }
  ]
}
const detailData = ref({})

function stripHtmlTags(html) {
  // 简单的去除HTML标签的函数
  return html.replace(/<[^>]*>/g, "")
}

function onSubmit() {
  formInlineRef.value?.validate((valid) => {
    if (valid) {
      const content = formInline.content
      // 去除HTML标签后检查内容是否为空
      const plainText = stripHtmlTags(content)
      if (plainText.trim() === "") {
        ElMessage.error("活动内容不能为空！")
      } else {
        const token = getToken()
        if (token) {
          createOrUpdateActivity(token)
        } else {
          router.push("/login")
        }
      }
    }
  })
}

function createOrUpdateActivity(token) {
  const params = {
    activity_id: route.query.id,
    title: formInline.title,
    image: formInline.image,
    content: formInline.content,
    font_color: formInline.font_color,
    token
  }
  createOrUpdateActivityDataApi(params).then((res) => {
    if (route.query.id) {
      ElMessage.success("活动编辑成功！")
      router.push({
        path: "/activity/details",
        query: { id: route.query.id }
      })
    } else {
      ElMessage.success("活动创建成功！")
      router.push({
        path: "/activity/list"
      })
    }
  })
}


function share() {
  const baseUrl = window.location.origin // 获取当前域名的基本 URL（协议 + 域名 + 端口）
  const fullPath = `${baseUrl}${"/dist/#/h5?id="}${route.query.id}` // 拼接完整的路由路径
  // 使用 window.open 在新标签页中打开该 URL
  window.open(fullPath, "_blank")
}

function fetch() {
  const params = {
    activity_id: route.query.id
  }
  getActivityDetailApi(params).then((res) => {
    if (res.data) {
      detailData.value = res.data
      formInline.title = res.data.title
      formInline.content = res.data.content
      formInline.image = res.data.image
      formInline.font_color = res.data.font_color
    }
  })
}

const mode = "default"
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 模拟 ajax 异步获取内容
onMounted(() => {
  if (route.query.id) {
    fetch()
  }
})

const toolbarConfig: any = { excludeKeys: "fullScreen" }
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      // 自定义上传配置
      customUpload: async (file, insertFn) => {
        // file 即选中的文件
        // insertFn 是获取图片url后，插入到编辑器的方法
        await yourUploadLogic(file, insertFn)
      },

      // 可选：上传前的校验
      allowedFileTypes: ['image/png', 'image/jpeg'],
      maxFileSize: 5 * 1024 * 1024, // 5M

      // 可选：自定义上传失败提示
      onError: (error) => {
        console.error('上传失败:', error)
        alert('图片上传失败，请重试')
      }
    },
    uploadVideo: {
      customUpload: async (file, insertFn) => {
        try {
          // 自定义上传逻辑
          const url = await uploadVideoToServer(file)
          insertFn(url) // 插入视频
        } catch (err) {
          console.error('视频上传失败:', err)
          throw err // 触发 onError
        }
      },
      allowedFileTypes: ['video/mp4', 'video/quicktime'], // 允许格式
      maxFileSize: 100 * 1024 * 1024, // 100MB
      onError: (error) => alert(`视频上传失败: ${error.message}`)
    }
  }
}

import axios from "axios"
const yourUploadLogic = async (file, insertFn) => {
  try {
    // 1. 构造 FormData
    const updateData = new FormData()
    // 字段名需与后端接口一致
    updateData.append('status', 2)
    updateData.append('file', file)
    // 2. 调用上传接口
    const res = await axios.post('https://gongyi.gaokaowin.com/api/common/upload', updateData)
    console.log('res-------------->', res.data)
    // 3. 处理响应
    // const data = await res.json()
    const data = await res.data
    // if (data.errno !== 0) throw new Error(data.message)

    // 4. 插入图片到编辑器
    insertFn(data.data, '图片描述') // 第二个参数是alt文本
  } catch (error) {
    console.error('Upload error:', error)
    throw error // 触发 onError
  }
}

const uploadVideoToServer = async (file) => {
  const videoData = new FormData()
  videoData.append('status', 2)
  videoData.append('file', file)

  // 带进度监听的上传
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()

    // 进度监听
    xhr.upload.addEventListener('progress', e => {
      const percent = Math.round((e.loaded / e.total) * 100)
      console.log(`上传进度: ${percent}%`)
    })

    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          const res = JSON.parse(xhr.responseText)
          resolve(res.data)
        } else {
          reject(new Error('上传失败'))
        }
      }
    }

    xhr.open('POST', 'https://gongyi.gaokaowin.com/api/common/upload')
    xhr.send(videoData)
  })
}

function handleCreated(editor) {
  // 记录 editor 实例，重要！
  editorRef.value = editor
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<template>
  <div class="app-container">
    <el-form ref="formInlineRef" :model="formInline" :rules="formInlineRules">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <div class="header-h1">
              <el-form-item label="活动标题" prop="title">
                <el-input v-model="formInline.title" placeholder="请输入标题" clearable />
              </el-form-item>
            </div>

            <div>
              <!-- <el-button type="primary" @click="share">
                预览活动
              </el-button> -->
              <el-button type="primary" @click="onSubmit">
                {{ route.query.id ? '编辑' : '创建' }}活动
              </el-button>
            </div>
          </div>
          <div>
            <el-text class="mx-1" type="info">
              发布人：<span class="mr-3">{{ detailData.admin_id }}</span>
              发布时间：<span>{{ detailData.createtime ? formatDateTime(detailData.createtime * 1000) : ''}}</span>
            </el-text>
          </div>
        </template>
        <div class="card-body">
          <div class="img-item">
            <el-form-item label="活动图片" prop="image">
              <!-- <el-input v-model="formInline.image" /> -->
              <SingleImageUpload v-model="formInline.image" />
            </el-form-item>
            <el-form-item label="弹幕颜色" prop="font_color">
              <el-color-picker v-model="formInline.font_color" class="ml-2" />
            </el-form-item>
          </div>

          <div class="wangeditor">
            <el-form-item label="活动内容" prop="content" class="editor-item">
              <Toolbar
                :editor="editorRef"
                :default-config="toolbarConfig"
                :mode="mode"
                style="border-bottom: 1px solid #ccc; width: 100%;"
              />
              <Editor
                v-model="formInline.content"
                :default-config="editorConfig"
                :mode="mode"
                style="height: 560px; width: 100%; overflow-y: hidden"
                @on-created="handleCreated"
              />
            </el-form-item>
          </div>
        </div>
      </el-card>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.card-header {
  display: flex;
  .header-h1 {
    flex: 1;
    margin-right: 15px;
  }
}
</style>
